<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div id="app">
        <h3>购物车</h3>
        <header-com></header-com>
        <footer-com></footer-com>
    </div>

    <!-- 头部 -->
    <template id="header">
        <ul>
            <li v-for="(item, index) in list">
                <p>
                    {{ item.title }}
                </p>
                <p>
                    <button @click="del(index)">--</button>
                    {{ item.count }}
                    <button @click="add(index)">+</button>
                </p>
                <p>
                    {{ item.price }}
                </p>
            </li>
        </ul>
    </template>

    <!-- 底部 -->
    <template id="footer">
        <div>
            总价格: {{ Number(price).toFixed(2) }}
        </div>
    </template>

    <script src="./js/vue.js"></script>
    <script>
        // 定义事件总线
        const bus = new Vue

        // 头部组件
        const HeaderCom = {
            template: "#header",
            data() {
                return {
                    list: [
                        {
                            title: "商品1",
                            count: 1,
                            price: 100
                        },
                        {
                            title: "商品2",
                            count: 1,
                            price: 50
                        }
                    ]
                }
            },
            methods: {
                del(index) {
                    this.list[index].count -= 1
                    bus.$emit('send', this.list)
                },
                add(index) {
                    this.list[index].count += 1
                    bus.$emit('send', this.list)
                }
            }
        }

         // 底部组件
        const FooterCom = {
            template: "#footer",
            data() {
                return {
                    price: null
                }
            },
            created() {
                bus.$on('send', (list) => {
                    this.price = list.reduce((prev, next) => {
                        return prev + next.count * next.price
                    }, 0)
                })
            }
        }
        new Vue({
            el: "#app",
            components: {
                HeaderCom,
                FooterCom
            }
        })
    </script>
</body>
</html>